package com.dc.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.DateUtil;
import com.dc.common.ResponseResultVO;
import com.dc.entity.MaintenanceRelation;
import com.dc.entity.WorkOrder;
import com.dc.entity.ro.MaintenanceWorkOrderRO;
import com.dc.entity.vo.MaintenanceVO;
import com.dc.entity.vo.RepairVO;
import com.dc.enums.OrderType;
import com.dc.mapper.MaintenanceRelationMapper;
import com.dc.mapper.WorkOrderMapper;
import com.dc.service.MaintenanceWorkOrderService;
import com.dc.util.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
public class MaintenanceWorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements MaintenanceWorkOrderService {

    @Resource
    private WorkOrderMapper workOrderMapper;
    @Resource
    private MaintenanceRelationMapper relationMapper;
    @Resource
    private RedisUtil redisUtil;


    @Override
    @Transactional
    public ResponseResultVO insertMaintenanceWorkOrder(MaintenanceWorkOrderRO ro) {

        /*List<WorkOrder> workOrders = workOrderMapper.selectList(new LambdaQueryWrapper<WorkOrder>()
                .eq(WorkOrder::getSerialNumber, ro.getSerialNumber())
                .eq(WorkOrder::getType, 1)
                .and(w -> {
                    w.eq(WorkOrder::getStatus, 0).or().eq(WorkOrder::getStatus, 1);
                }));
        if (!workOrders.isEmpty() && workOrders.size() > 0) {
            return ResponseResultVO.failResult(String.format("设备【%s】,已提交维保,请勿重复提交!", ro.getSerialNumber()));
        }*/

        // 查看有设备故障信息
        LambdaQueryWrapper<WorkOrder> wrapper = new LambdaQueryWrapper<WorkOrder>()
                .eq(WorkOrder::getSerialNumber, ro.getSerialNumber())
                .eq(WorkOrder::getType, 0).eq(WorkOrder::getStatus, 0)
                .orderByAsc(WorkOrder::getCreateTime);
        WorkOrder ww = workOrderMapper.selectOne(wrapper);
        if (null == ww) {
            return ResponseResultVO.failResult(String.format("设备【%s】,暂未发现故障信息,无法维保!", ro.getSerialNumber()));
        }

        WorkOrder maintenanceWorkOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, maintenanceWorkOrder);
        maintenanceWorkOrder.setId(SnowflakeIdWorker.generateId());
        //maintenanceWorkOrder.setReportUserId(Long.valueOf(UserUtil.getUserId()));
        //maintenanceWorkOrder.setReportUserName(String.valueOf(redisUtil.get(UserUtil.getUserId())));
        maintenanceWorkOrder.setType(OrderType.MAINTENANCE.getId());

        // 时间判断
        Date dateStart = DateUtil.parseStrToDate(ro.getStartTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        Date dateEnd = DateUtil.parseStrToDate(ro.getEndTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        if (dateStart.getTime() > dateEnd.getTime()) {
            return ResponseResultVO.failResult("开始时间不能大于结束时间");
        }
        Date dateToday = new Date();
        if (dateEnd.getTime() < dateToday.getTime()) {
            return ResponseResultVO.failResult("结束时间不能小于当前时间");
        }

        if (dateStart.getTime() > dateToday.getTime()) {
            maintenanceWorkOrder.setStatus(0);
        }
        if (dateStart.getTime() <= dateToday.getTime() && dateEnd.getTime() >= dateToday.getTime()) {
            maintenanceWorkOrder.setStatus(1);
        }

        WorkOrder wo = new WorkOrder();
        wo.setStatus(2);
        int update = workOrderMapper.update(wo, wrapper);
        if (update < 1) {
            return ResponseResultVO.updateResult(update);
        }
        maintenanceWorkOrder.setNumber(redisUtil.serialNumber("WB"));
        // 维保开始-结束
        maintenanceWorkOrder.setStartTime(dateStart);
        maintenanceWorkOrder.setEndTime(dateEnd);
        // 本次维保时间
        if (StringUtils.isNotBlank(ro.getRecTime())) {
            maintenanceWorkOrder.setRecTime(DateUtil.parseStrToDate(ro.getRecTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        }
        if (StringUtils.isNotBlank(ro.getNextTime())) {
            maintenanceWorkOrder.setNextTime(DateUtil.parseStrToDate(ro.getNextTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        }
        if (CollectionUtils.isNotEmpty(ro.getMaintenanceRelation())) {
            for (MaintenanceRelation dto : ro.getMaintenanceRelation()) {
                dto.setId(SnowflakeIdWorker.generateId());
                dto.setMaintenanceWorkId(maintenanceWorkOrder.getId());
                relationMapper.insert(dto);
            }
        }
        return ResponseResultVO.insertResult(workOrderMapper.insert(maintenanceWorkOrder));
    }

    @Override
    @Transactional
    public ResponseResultVO updateMaintenanceWorkOrder(MaintenanceWorkOrderRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        WorkOrder maintenanceWorkOrder = new WorkOrder();
        BeanUtils.copyProperties(ro, maintenanceWorkOrder);
        if (StringUtils.isNotBlank(ro.getRecTime())) {
            maintenanceWorkOrder.setRecTime(DateUtil.parseStrToDate(ro.getRecTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        }
        if (StringUtils.isNotBlank(ro.getNextTime())) {
            maintenanceWorkOrder.setNextTime(DateUtil.parseStrToDate(ro.getNextTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        }
        relationMapper.delete(new QueryWrapper<MaintenanceRelation>().lambda().eq(MaintenanceRelation::getMaintenanceWorkId, ro.getId()));
        if (CollectionUtils.isNotEmpty(ro.getMaintenanceRelation())) {
            for (MaintenanceRelation dto : ro.getMaintenanceRelation()) {
                dto.setId(SnowflakeIdWorker.generateId());
                dto.setMaintenanceWorkId(ro.getId());
                relationMapper.insert(dto);
            }
        }

        return ResponseResultVO.updateResult(workOrderMapper.updateById(maintenanceWorkOrder));
    }

    @Override
    @Transactional
    public ResponseResultVO deleteMaintenanceWorkOrder(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        relationMapper.delete(new QueryWrapper<MaintenanceRelation>().lambda().in(MaintenanceRelation::getMaintenanceWorkId, idList));
        return ResponseResultVO.deleteResult(workOrderMapper.deleteBatchIds(idList));
    }

    @Override
    public ResponseResultVO selectMaintenanceWorkOrderList(MaintenanceWorkOrderRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WorkOrder::getType, OrderType.MAINTENANCE.getId());
        queryWrapper.lambda().in(CollectionUtils.isNotEmpty(ro.getIds()), WorkOrder::getId, ro.getIds());
        queryWrapper.orderBy(StringUtils.isNotBlank(ro.getOrderByColumn()), "asc".equalsIgnoreCase(ro.getIsAsc()) ? true : false, StringUtils.toLine(ro.getOrderByColumn()));
        queryWrapper.lambda().eq(StringUtils.isNotBlank(ro.getRegionName()), WorkOrder::getRegionName, ro.getRegionName());
        queryWrapper.lambda().eq(null != ro.getStatus(), WorkOrder::getStatus, ro.getStatus());
        queryWrapper.apply(StrUtil.isNotBlank(ro.getCreateTime()),
                "date_format (create_time,'%Y-%m-%d') = date_format('" + ro.getCreateTime() + "','%Y-%m-%d')");
        Page<WorkOrder> selectPage = workOrderMapper.selectPage(page, queryWrapper);
        List<MaintenanceVO> maintenanceVOList = ListBeanUtils.listCopyMapper(selectPage.getRecords(), WorkOrder.class, MaintenanceVO.class);
        if (CollectionUtils.isNotEmpty(maintenanceVOList)) {
            List<MaintenanceRelation> maintenanceRelations = relationMapper.selectList(new QueryWrapper<MaintenanceRelation>().lambda()
                    .in(MaintenanceRelation::getMaintenanceWorkId, maintenanceVOList.stream().map(MaintenanceVO::getId).collect(Collectors.toSet())));
            maintenanceVOList.forEach(s -> {
                s.setInfo(maintenanceRelations.stream().filter(f -> f.getMaintenanceWorkId().equals(s.getId())).collect(Collectors.toList()));
            });
        }
        return ResponseResultVO.resultPageList(maintenanceVOList, ro);

    }

    @Override
    public void maintenanceWorkOrderExport(HttpServletResponse response, MaintenanceWorkOrderRO ro) {
        //支持百万级别数据excel导出,每页10000循环写入
        String excelName = "维保记录";
        ExportParams exportParams = new ExportParams(excelName, "");
        exportParams.setStyle(ExcelExportStyler.class);
        Workbook workbook = ExcelExportUtil.exportBigExcel(exportParams,
                MaintenanceVO.class, (queryParams, page) -> {
                    //page每次加一，当等于obj的值时返回空，代码结束；
                    //源码得知page初始值是1,自动递增
                    if (((int) queryParams) == page) {
                        return null;
                    }
                    List<Object> list = new ArrayList<>();
                    Page pages = new Page<Map<String, Object>>(page, 10000);
                    QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(WorkOrder::getType, 1);
                    queryWrapper.lambda().in(CollectionUtils.isNotEmpty(ro.getIds()), WorkOrder::getId, ro.getIds());
                    queryWrapper.orderBy(StringUtils.isNotBlank(ro.getOrderByColumn()), "asc".equalsIgnoreCase(ro.getIsAsc()) ? true : false, StringUtils.toLine(ro.getOrderByColumn()));
                    Page<WorkOrder> selectPage = workOrderMapper.selectPage(pages, queryWrapper);
                    List<MaintenanceVO> maintenanceVOList = ListBeanUtils.listCopyMapper(selectPage.getRecords(), WorkOrder.class, MaintenanceVO.class);
                    if (CollectionUtils.isNotEmpty(maintenanceVOList)) {
                        List<MaintenanceRelation> maintenanceRelations = relationMapper.selectList(new QueryWrapper<MaintenanceRelation>().lambda().in(MaintenanceRelation::getMaintenanceWorkId, maintenanceVOList.stream().map(MaintenanceVO::getId).collect(Collectors.toSet())));
                        maintenanceVOList.forEach(s -> {
                            s.setInfo(maintenanceRelations.stream().filter(f -> f.getMaintenanceWorkId().equals(s.getId())).collect(Collectors.toList()));
                            list.add(s);
                        });
                    }
                    return list;
                }, (ro.getPageSize() / 10000) + 1 + 1); //ro.getPageSize()传总数，queryParams的值需要额外+1，避免1 = 1跳过查询
        ExportUtil.exportSetCode(workbook, excelName, response);

    }
}
